import { useUserStore } from '@/store/user';
import { createRouter, createWebHistory } from 'vue-router';


const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      // 布局页面
      path: '/',
      redirect: '/index',
      component: () => import('@/views/Layout/index.vue'),
      children: [
        {
          // 首页
          path: 'index',
          redirect: 'dashboard',
          component: () => import('@/views/Layout/index.vue')
        },
        {
          // 文章管理
          path: 'article',
          component: () => import('@/views/Article/index.vue'),
        },
        {
          // 仪表盘
          path: 'dashboard',
          component: () => import('@/views/Dashboard/index.vue'),
        }
      ]
    },
    {
      // 登录页面
      path: '/login',
      component: () => import('@/views/Login/index.vue')
    },
    {
      // 404
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/_404/index.vue')

    }
  ]
})

const whiteRoute = ['/login']

router.beforeEach((to) => {
  const { token } = useUserStore()

  if (token) {
    // 有token
    if (to.path === '/login') {
      // 不是停止 而是返回到首页
      return '/'
    } else {
      return true
    }
  }
  // 没有 token
  if (whiteRoute.includes(to.path)) {
    // 在白名单下
    return true
  } else {
    return `/login?redirectUrl=${to.path}`
  }
})

export default router